const dayjs = require('dayjs');
const ResearchProjectModel = require('../model/research_project_model.js');

/**
 * 项目数据处理业务逻辑类
 * 统一处理项目数据格式，确保前后端数据一致性
 */
class ProjectDataBiz {
  /**
   * 检查ResearchProjectModel是否正确引入
   * @returns {Boolean} 是否正确引入
   * @private
   */
  static _isModelAvailable() {
    try {
      return ResearchProjectModel && typeof ResearchProjectModel === 'function';
    } catch (e) {
      console.error('ResearchProjectModel未正确引入:', e);
      return false;
    }
  }

  /**
   * 标准化项目数据
   * @param {Object} project 项目数据对象
   * @returns {Object} 标准化后的项目数据
   */
  static formatProjectData(project) {
    if (!project) return null;
    
    // 确保ResearchProjectModel.FIELD_PREFIX可用，默认使用"PROJECT_"作为前缀
    const PREFIX = (ResearchProjectModel && ResearchProjectModel.FIELD_PREFIX) ? 
                   ResearchProjectModel.FIELD_PREFIX : 'PROJECT_';
    
    const STATUS_FIELD = (ResearchProjectModel && ResearchProjectModel.STATUS_FIELD) ?
                        ResearchProjectModel.STATUS_FIELD : 'PROJECT_STATUS';
    
    const SUB_STATUS_FIELD = (ResearchProjectModel && ResearchProjectModel.SUB_STATUS_FIELD) ?
                            ResearchProjectModel.SUB_STATUS_FIELD : 'PROJECT_SUB_STATUS';
    
    const ACTIVE_STATE_FIELD = (ResearchProjectModel && ResearchProjectModel.ACTIVE_STATE_FIELD) ?
                              ResearchProjectModel.ACTIVE_STATE_FIELD : 'PROJECT_ACTIVE_STATE';
    
    const ACTIVE_SUB_STATE_FIELD = (ResearchProjectModel && ResearchProjectModel.ACTIVE_SUB_STATE_FIELD) ?
                                  ResearchProjectModel.ACTIVE_SUB_STATE_FIELD : 'PROJECT_ACTIVE_SUB_STATE';
    
    // 使用确定的前缀构建标准化数据
    const standardProject = {
      _id: project._id || '',
      
      // 基本信息
      [PREFIX + 'CODE']: project[PREFIX + 'CODE'] || project.code || '',
      [PREFIX + 'NAME']: project[PREFIX + 'NAME'] || project.model || project.title || '',
      [PREFIX + 'DESC']: project[PREFIX + 'DESC'] || project.description || '',
      [PREFIX + 'CUSTOMER_NAME']: project[PREFIX + 'CUSTOMER_NAME'] || project.customerName || '',
      
      // 兼容新的应用类型字段
      applicationType: project.applicationType || '',
      customerName: project.customerName || project[PREFIX + 'CUSTOMER_NAME'] || '',
      model: project.model || project[PREFIX + 'CODE'] || '',
      description: project.description || project[PREFIX + 'DESC'] || '',
      
      // 状态信息
      [STATUS_FIELD]: typeof project[STATUS_FIELD] !== 'undefined' ? project[STATUS_FIELD] : (project.status || 0),
      [SUB_STATUS_FIELD]: project[SUB_STATUS_FIELD] || project.subStatus || '',
      [ACTIVE_STATE_FIELD]: project[ACTIVE_STATE_FIELD] || project.activeState || '',
      [ACTIVE_SUB_STATE_FIELD]: project[ACTIVE_SUB_STATE_FIELD] || project.activeSubState || '',
      [PREFIX + 'STATUS_DESC']: project[PREFIX + 'STATUS_DESC'] || '',
      
      // 分类信息
      [PREFIX + 'CATE']: typeof project[PREFIX + 'CATE'] !== 'undefined' ? project[PREFIX + 'CATE'] : (project.cate || 0),
      [PREFIX + 'PRIORITY']: typeof project[PREFIX + 'PRIORITY'] !== 'undefined' ? project[PREFIX + 'PRIORITY'] : (project.priority || 1),
      
      // 进度信息
      [PREFIX + 'PROGRESS']: typeof project[PREFIX + 'PROGRESS'] !== 'undefined' ? project[PREFIX + 'PROGRESS'] : (project.progress || 0),
      
      // 时间信息
      [PREFIX + 'START_DATE']: this._normalizeTimestamp(project[PREFIX + 'START_DATE'] || project.startDate || ''),
      [PREFIX + 'END_DATE']: this._normalizeTimestamp(project[PREFIX + 'END_DATE'] || project.endDate || ''),
      [PREFIX + 'PLAN_START_DATE']: this._normalizeTimestamp(project[PREFIX + 'PLAN_START_DATE'] || project.startDate || ''),
      [PREFIX + 'PLAN_END_DATE']: this._normalizeTimestamp(project[PREFIX + 'PLAN_END_DATE'] || project.deadline || project.endDate || ''),
      
      // 负责人信息
      [PREFIX + 'MANAGER_ID']: project[PREFIX + 'MANAGER_ID'] || project.managerId || '',
      [PREFIX + 'MANAGER_NAME']: project[PREFIX + 'MANAGER_NAME'] || project.managerName || '',
      
      // 时间戳
      CREATE_TIME: project.CREATE_TIME || project.createTime || dayjs().valueOf(),
      UPDATE_TIME: project.UPDATE_TIME || project.updateTime || dayjs().valueOf(),
      
      // 确保项目标题字段一致
      PROJECT_TITLE: project.PROJECT_TITLE || project[PREFIX + 'NAME'] || project.model || project.title || ''
    };
    
    // 处理日期显示格式字段
    standardProject.PROJECT_PLAN_START_DATE_DISPLAY = this.formatDateDisplay(standardProject[PREFIX + 'PLAN_START_DATE']);
    standardProject.PROJECT_PLAN_END_DATE_DISPLAY = this.formatDateDisplay(standardProject[PREFIX + 'PLAN_END_DATE']);
    
    // 获取状态描述（替换对getFullStatusDesc的调用）
    if (!standardProject[PREFIX + 'STATUS_DESC']) {
      try {
        // 优先尝试使用ResearchProjectModel.getFullStatusDesc
        if (this._isModelAvailable() && typeof ResearchProjectModel.getFullStatusDesc === 'function') {
          standardProject[PREFIX + 'STATUS_DESC'] = ResearchProjectModel.getFullStatusDesc(standardProject);
        } else {
          // 备用状态描述生成
          standardProject[PREFIX + 'STATUS_DESC'] = this._generateStatusDesc(standardProject, PREFIX, STATUS_FIELD, SUB_STATUS_FIELD, ACTIVE_STATE_FIELD, ACTIVE_SUB_STATE_FIELD);
        }
      } catch (e) {
        console.error('生成状态描述失败:', e);
        standardProject[PREFIX + 'STATUS_DESC'] = this._generateStatusDesc(standardProject, PREFIX, STATUS_FIELD, SUB_STATUS_FIELD, ACTIVE_STATE_FIELD, ACTIVE_SUB_STATE_FIELD);
      }
    }
    
    // 确保进度以整数形式显示
    standardProject[PREFIX + 'PROGRESS'] = this.formatProgress(standardProject[PREFIX + 'PROGRESS']);
    
    return standardProject;
  }
  
  /**
   * 生成项目状态描述
   * @param {Object} project 项目数据
   * @param {String} prefix 字段前缀
   * @param {String} statusField 状态字段
   * @param {String} subStatusField 子状态字段
   * @param {String} activeStateField 活动状态字段
   * @param {String} activeSubStateField 活动子状态字段
   * @returns {String} 状态描述文本
   * @private
   */
  static _generateStatusDesc(project, prefix, statusField, subStatusField, activeStateField, activeSubStateField) {
    if (!project) return '未知状态';
    
    const status = project[statusField];
    const subStatus = project[subStatusField];
    const activeState = project[activeStateField];
    const activeSubState = project[activeSubStateField];
    
    // 简单状态描述生成逻辑
    switch (status) {
      case 0: return '待立项';
      case 1: return '项目审核中';
      case 2: return '休眠中';
      case 3: return '活动中';
      case 99: return '已完成';
      default: return '未知状态';
    }
  }
  
  /**
   * 格式化项目列表数据
   * @param {Array} projectList 项目列表数据
   * @returns {Array} 标准化后的项目列表数据
   */
  static formatProjectList(projectList) {
    if (!projectList || !Array.isArray(projectList)) return [];
    return projectList.map(item => this.formatProjectData(item));
  }
  
  /**
   * 准备项目提交数据
   * @param {Object} formData 表单数据
   * @param {Object} projectData 原项目数据（如果是编辑模式）
   * @returns {Object} 准备好的提交数据
   */
  static prepareSubmitData(formData, projectData = {}) {
    if (!formData) return {};
    
    // 确定是否为编辑模式
    const isEdit = projectData && projectData._id;
    
    // 确保ResearchProjectModel.FIELD_PREFIX可用，默认使用"PROJECT_"作为前缀
    const PREFIX = (ResearchProjectModel && ResearchProjectModel.FIELD_PREFIX) ? 
                   ResearchProjectModel.FIELD_PREFIX : 'PROJECT_';
    
    const STATUS_FIELD = (ResearchProjectModel && ResearchProjectModel.STATUS_FIELD) ?
                        ResearchProjectModel.STATUS_FIELD : 'PROJECT_STATUS';
    
    const SUB_STATUS_FIELD = (ResearchProjectModel && ResearchProjectModel.SUB_STATUS_FIELD) ?
                            ResearchProjectModel.SUB_STATUS_FIELD : 'PROJECT_SUB_STATUS';
    
    const ACTIVE_STATE_FIELD = (ResearchProjectModel && ResearchProjectModel.ACTIVE_STATE_FIELD) ?
                              ResearchProjectModel.ACTIVE_STATE_FIELD : 'PROJECT_ACTIVE_STATE';
    
    const ACTIVE_SUB_STATE_FIELD = (ResearchProjectModel && ResearchProjectModel.ACTIVE_SUB_STATE_FIELD) ?
                                  ResearchProjectModel.ACTIVE_SUB_STATE_FIELD : 'PROJECT_ACTIVE_SUB_STATE';
    
    // 基础数据
    const submitData = {
      // 使用确定的前缀字段
      [PREFIX + 'CODE']: formData[PREFIX + 'CODE'] || formData.code || this._generateProjectCode(),
      [PREFIX + 'DESC']: formData[PREFIX + 'DESC'] || formData.description || '',
      [PREFIX + 'CATE']: formData[PREFIX + 'CATE'] !== undefined ? formData[PREFIX + 'CATE'] : (formData.cate || 0),
      [PREFIX + 'PRIORITY']: formData[PREFIX + 'PRIORITY'] !== undefined ? formData[PREFIX + 'PRIORITY'] : (formData.priority || 'medium'),
      [PREFIX + 'CUSTOMER_NAME']: formData[PREFIX + 'CUSTOMER_NAME'] || formData.customerName || '',
      
      // 活动状态信息
      [ACTIVE_STATE_FIELD]: formData[ACTIVE_STATE_FIELD] || formData.activeState || 'planning',
      [ACTIVE_SUB_STATE_FIELD]: formData[ACTIVE_SUB_STATE_FIELD] || formData.activeSubState || 'init',
      
      // 添加应用类型字段
      applicationType: formData.applicationType || '',
      customerName: formData.customerName || formData[PREFIX + 'CUSTOMER_NAME'] || '',
      
      // 重要：添加项目负责人字段，这是后端验证必需的
      leader: formData.leader || formData[PREFIX + 'MANAGER_NAME'] || '张工',
      
      // 重要：添加部门字段，这是后端可能需要的字段
      department: formData.department || '研发部',
      
      // 重要：添加优先级字段，符合后端验证要求
      priority: formData.priority || 'normal',
      
      // 重要：添加状态字段，符合后端验证要求
      status: formData.status || 'planning',
      
      // 项目名称字段，必须提供
      [PREFIX + 'NAME']: formData[PREFIX + 'NAME'] || formData.PROJECT_TITLE || formData.title || formData.projectName || '',
      
      // 确保model字段存在，这是后端控制器需要的关键字段
      model: formData.model || formData.code || formData[PREFIX + 'CODE'] || '',
      
      // 时间信息 - 确保转换为时间戳
      [PREFIX + 'START_DATE']: this._normalizeTimestamp(formData[PREFIX + 'START_DATE'] || formData.startDate || dayjs().valueOf()),
      [PREFIX + 'END_DATE']: this._normalizeTimestamp(formData[PREFIX + 'END_DATE'] || formData.deadline || formData.endDate || dayjs().valueOf()),
      [PREFIX + 'PLAN_START_DATE']: this._normalizeTimestamp(formData[PREFIX + 'PLAN_START_DATE'] || formData.startDate || dayjs().valueOf()),
      [PREFIX + 'PLAN_END_DATE']: this._normalizeTimestamp(formData[PREFIX + 'PLAN_END_DATE'] || formData.deadline || formData.endDate || dayjs().valueOf()),
      
      // 重要：确保开始日期和截止日期字段存在，这是后端验证必需的
      startDate: this._normalizeTimestamp(formData.startDate || formData[PREFIX + 'START_DATE'] || formData[PREFIX + 'PLAN_START_DATE'] || dayjs().valueOf()),
      deadline: this._normalizeTimestamp(formData.deadline || formData.endDate || formData[PREFIX + 'END_DATE'] || formData[PREFIX + 'PLAN_END_DATE'] || (dayjs().valueOf() + 7 * 24 * 60 * 60 * 1000)),
      
      // 产品参数
      workTemp: formData.workTemp || '0~70',
      certification: formData.certification || '无',
      lowPower: formData.lowPower || '无',
      startupTime: formData.startupTime || '',
      conformalCoating: formData.conformalCoating || '无',
      ratedVoltage: formData.ratedVoltage || '',
      maxPower: formData.maxPower || '',
      maxSpeed: formData.maxSpeed || '',
      polePairs: formData.polePairs || '',
      hasHall: formData.hasHall || '无',
      controlMode: formData.controlMode || '',
      controlAlgorithm: formData.controlAlgorithm || '',
      rotation: formData.rotation || '无',
      hasBrake: formData.hasBrake || '无',
      hasFG: formData.hasFG || '无',
      
      // 保护参数
      stallProtection: formData.stallProtection || '无',
      overvoltageProtection: formData.overvoltageProtection || '无',
      undervoltageProtection: formData.undervoltageProtection || '无',
      temperatureProtection: formData.temperatureProtection || '无',
      overcurrentProtection: formData.overcurrentProtection || '无',
      currentLimitProtection: formData.currentLimitProtection || '无',
      blockageProtection: formData.blockageProtection || '无',
      phaseProtection: formData.phaseProtection || '无',
      
      // 确保更新时间
      UPDATE_TIME: dayjs().valueOf()
    };
    
    // 确保项目标题不为空
    if (!submitData[PREFIX + 'NAME']) {
      submitData[PREFIX + 'NAME'] = submitData[PREFIX + 'CODE'] || this._generateProjectCode();
    }
    
    // 兼容PROJECT_TITLE字段（确保和PROJECT_NAME保持一致）
    submitData.PROJECT_TITLE = submitData[PREFIX + 'NAME'];
    
    // 如果是新项目，设置默认状态
    if (!isEdit) {
      submitData[STATUS_FIELD] = 1; // 项目审核
      submitData[SUB_STATUS_FIELD] = 'director'; // 董事长
      submitData[PREFIX + 'PROGRESS'] = 0;
      submitData.CREATE_TIME = dayjs().valueOf();
    }
    
    return submitData;
  }
  
  /**
   * 生成唯一的项目代码
   * @returns {String} 生成的项目代码
   * @private
   */
  static _generateProjectCode() {
    // 创建基于时间的项目代码格式：PRJ + 年月日 + 3位随机数
    const now = dayjs();
    const year = now.year();
    const month = String(now.month() + 1).padStart(2, '0');
    const day = String(now.date()).padStart(2, '0');
    const random = Math.floor(Math.random() * 1000).format("YYYY-MM-DD HH:mm:ss").padStart(3, '0');
    
    return `PRJ${year}${month}${day}${random}`;
  }
  
  /**
   * 提取用于显示的项目数据
   * @param {Object} project 完整项目数据
   * @returns {Object} 用于UI显示的数据 
   */
  static extractUIData(project) {
    if (!project) return {};
    
    const standardProject = this.formatProjectData(project);
    
    // 只返回UI需要的字段
    return {
      _id: standardProject._id,
      [ResearchProjectModel.FIELD_PREFIX + 'CODE']: standardProject[ResearchProjectModel.FIELD_PREFIX + 'CODE'],
      [ResearchProjectModel.FIELD_PREFIX + 'NAME']: standardProject[ResearchProjectModel.FIELD_PREFIX + 'NAME'],
      [ResearchProjectModel.FIELD_PREFIX + 'DESC']: standardProject[ResearchProjectModel.FIELD_PREFIX + 'DESC'],
      [ResearchProjectModel.FIELD_PREFIX + 'CUSTOMER_NAME']: standardProject[ResearchProjectModel.FIELD_PREFIX + 'CUSTOMER_NAME'],
      [ResearchProjectModel.FIELD_PREFIX + 'CATE']: standardProject[ResearchProjectModel.FIELD_PREFIX + 'CATE'],
      [ResearchProjectModel.FIELD_PREFIX + 'PRIORITY']: standardProject[ResearchProjectModel.FIELD_PREFIX + 'PRIORITY'],
      [ResearchProjectModel.STATUS_FIELD]: standardProject[ResearchProjectModel.STATUS_FIELD],
      [ResearchProjectModel.SUB_STATUS_FIELD]: standardProject[ResearchProjectModel.SUB_STATUS_FIELD],
      [ResearchProjectModel.ACTIVE_STATE_FIELD]: standardProject[ResearchProjectModel.ACTIVE_STATE_FIELD],
      [ResearchProjectModel.ACTIVE_SUB_STATE_FIELD]: standardProject[ResearchProjectModel.ACTIVE_SUB_STATE_FIELD],
      [ResearchProjectModel.FIELD_PREFIX + 'STATUS_DESC']: standardProject[ResearchProjectModel.FIELD_PREFIX + 'STATUS_DESC'],
      [ResearchProjectModel.FIELD_PREFIX + 'PROGRESS']: standardProject[ResearchProjectModel.FIELD_PREFIX + 'PROGRESS'],
      PROJECT_PLAN_START_DATE_DISPLAY: standardProject.PROJECT_PLAN_START_DATE_DISPLAY,
      PROJECT_PLAN_END_DATE_DISPLAY: standardProject.PROJECT_PLAN_END_DATE_DISPLAY,
      [ResearchProjectModel.FIELD_PREFIX + 'MANAGER_NAME']: standardProject[ResearchProjectModel.FIELD_PREFIX + 'MANAGER_NAME'],
      
      // 添加辅助属性：分类名称
      typeName: ResearchProjectModel.getCateName(standardProject[ResearchProjectModel.FIELD_PREFIX + 'CATE']),
      priorityName: ResearchProjectModel.getPriorityName(standardProject[ResearchProjectModel.FIELD_PREFIX + 'PRIORITY']),
    };
  }
  
  /**
   * 格式化项目进度
   * @param {Number|String} progress 进度值
   * @returns {Number} 格式化后的进度值
   */
  static formatProgress(progress) {
    if (typeof progress === 'undefined' || progress === null) return 0;
    if (typeof progress === 'string') {
      // 如果是百分比格式，去掉百分号
      progress = progress.replace('%', '');
    }
    return Number(progress);
  }
  
  /**
   * 格式化日期显示
   * @param {Number|String|Date} timestamp 时间戳或日期
   * @returns {String} 格式化后的日期字符串
   */
  static formatDateDisplay(timestamp) {
    if (!timestamp) return '';
    
    // 标准化时间戳
    const normalizedTimestamp = this._normalizeTimestamp(timestamp);
    if (!normalizedTimestamp) return '';
    
    try {
      const date = dayjs(normalizedTimestamp);
      
      // 检查日期是否有效
      if (!date.isValid()) return '';
      
      return date.format('YYYY-MM-DD');
    } catch (e) {
      console.error('日期格式化错误:', e);
      return '';
    }
  }
  
  /**
   * 标准化时间戳
   * @param {Number|String|Date} timestamp 时间戳或日期
   * @returns {Number} 标准化的毫秒级时间戳
   * @private
   */
  static _normalizeTimestamp(timestamp) {
    if (!timestamp) return dayjs().valueOf(); // 默认返回当前时间
    
    if (timestamp instanceof Date) {
      return timestamp.getTime();
    }
    
    if (typeof timestamp === 'string') {
      // 尝试解析日期字符串
      if (timestamp.match(/^\d{4}-\d{2}-\d{2}/)) {
        return dayjs(timestamp.replace(/-/g, '/')).valueOf();
      }
      // 尝试将数字字符串转换为数字
      if (!isNaN(timestamp)) {
        const num = Number(timestamp);
        // 如果是秒级时间戳，转换为毫秒级
        if (num < 10000000000) {
          return num * 1000;
        }
        return num;
      }
    }
    
    if (typeof timestamp === 'number') {
      // 如果是秒级时间戳，转换为毫秒级
      if (timestamp < 10000000000) {
        return timestamp * 1000;
      }
      return timestamp;
    }
    
    // 无法解析的情况下返回当前时间
    return dayjs().valueOf();
  }
  
  /**
   * 创建用于全局存储的项目数据
   * @param {Object} project 项目数据
   * @returns {Object} 标准化的全局项目数据
   */
  static createGlobalProject(project) {
    if (!project) return null;
    
    // 确保ResearchProjectModel.FIELD_PREFIX可用，默认使用"PROJECT_"作为前缀
    const PREFIX = (ResearchProjectModel && ResearchProjectModel.FIELD_PREFIX) ? 
                   ResearchProjectModel.FIELD_PREFIX : 'PROJECT_';
    
    const STATUS_FIELD = (ResearchProjectModel && ResearchProjectModel.STATUS_FIELD) ?
                        ResearchProjectModel.STATUS_FIELD : 'PROJECT_STATUS';
    
    const SUB_STATUS_FIELD = (ResearchProjectModel && ResearchProjectModel.SUB_STATUS_FIELD) ?
                            ResearchProjectModel.SUB_STATUS_FIELD : 'PROJECT_SUB_STATUS';
    
    const ACTIVE_STATE_FIELD = (ResearchProjectModel && ResearchProjectModel.ACTIVE_STATE_FIELD) ?
                              ResearchProjectModel.ACTIVE_STATE_FIELD : 'PROJECT_ACTIVE_STATE';
    
    const ACTIVE_SUB_STATE_FIELD = (ResearchProjectModel && ResearchProjectModel.ACTIVE_SUB_STATE_FIELD) ?
                                  ResearchProjectModel.ACTIVE_SUB_STATE_FIELD : 'PROJECT_ACTIVE_SUB_STATE';
    
    // 提取项目基本信息
    const globalProject = {
      _id: project._id,
      title: project.PROJECT_TITLE || project[PREFIX + 'NAME'] || project.model || '',
      code: project[PREFIX + 'CODE'] || project.code || '',
      model: project[PREFIX + 'NAME'] || project.model || project.PROJECT_TITLE || '',
      status: project[STATUS_FIELD] || project.status || 0,
      subStatus: project[SUB_STATUS_FIELD] || project.subStatus || '',
      activeState: project[ACTIVE_STATE_FIELD] || project.activeState || '',
      activeSubState: project[ACTIVE_SUB_STATE_FIELD] || project.activeSubState || '',
      priority: project[PREFIX + 'PRIORITY'] || project.priority || 0,
      customerName: project[PREFIX + 'CUSTOMER_NAME'] || project.customerName || '',
      applicationType: project.applicationType || '',
      description: project[PREFIX + 'DESC'] || project.description || '',
      progress: project[PREFIX + 'PROGRESS'] || project.progress || 0,
      
      // 时间信息，确保是时间戳格式
      startDate: project[PREFIX + 'PLAN_START_DATE'] || project[PREFIX + 'START_DATE'] || project.startDate || '',
      deadline: project[PREFIX + 'PLAN_END_DATE'] || project[PREFIX + 'END_DATE'] || project.deadline || '',
      createTime: project.CREATE_TIME || project.createTime || dayjs().valueOf(),
      
      // 保留原始字段以供详情页面使用
      [PREFIX + 'START_DATE']: project[PREFIX + 'START_DATE'] || this._normalizeTimestamp(project.startDate) || '',
      [PREFIX + 'END_DATE']: project[PREFIX + 'END_DATE'] || this._normalizeTimestamp(project.deadline || project.endDate) || '',
      [PREFIX + 'PLAN_START_DATE']: project[PREFIX + 'PLAN_START_DATE'] || this._normalizeTimestamp(project.startDate) || '',
      [PREFIX + 'PLAN_END_DATE']: project[PREFIX + 'PLAN_END_DATE'] || this._normalizeTimestamp(project.deadline) || '',
      
      // 产品参数
      workTemp: project.workTemp || '0~70',
      certification: project.certification || '无',
      lowPower: project.lowPower || '无',
      startupTime: project.startupTime || '',
      conformalCoating: project.conformalCoating || '无',
      ratedVoltage: project.ratedVoltage || '',
      maxPower: project.maxPower || '',
      maxSpeed: project.maxSpeed || '',
      polePairs: project.polePairs || '',
      hasHall: project.hasHall || '无',
      controlMode: project.controlMode || '',
      controlAlgorithm: project.controlAlgorithm || '',
      rotation: project.rotation || '无',
      hasBrake: project.hasBrake || '无',
      hasFG: project.hasFG || '无',
      
      // 保护参数
      stallProtection: project.stallProtection || '无',
      overvoltageProtection: project.overvoltageProtection || '无',
      undervoltageProtection: project.undervoltageProtection || '无',
      temperatureProtection: project.temperatureProtection || '无',
      overcurrentProtection: project.overcurrentProtection || '无',
      currentLimitProtection: project.currentLimitProtection || '无',
      blockageProtection: project.blockageProtection || '无',
      phaseProtection: project.phaseProtection || '无',
    };
    
    // 创建显示用的时间字符串
    globalProject.startDateDisplay = this.formatDateDisplay(globalProject.startDate);
    globalProject.endDateDisplay = this.formatDateDisplay(globalProject.deadline);
    globalProject.createTimeDisplay = this.formatDateDisplay(globalProject.createTime);
    
    return globalProject;
  }
  
  /**
   * 根据项目类型获取表单配置
   * @param {String} type 项目类型
   * @returns {Object} 表单配置
   */
  static getFormConfigByType(type) {
    try {
      // 使用统一配置入口模式
      const { ProjectService } = require('../../config/services_config');
      
      if (ProjectService && typeof ProjectService.getProjectFormConfig === 'function') {
        // 调用ProjectService的getProjectFormConfig方法
        return ProjectService.getProjectFormConfig(type);
      } else {
        // 如果方法不存在，返回默认配置
        console.log('ProjectService.getProjectFormConfig方法不存在，使用默认配置');
        return {
          showBasicFields: true,
          showControlFields: true,
          showProtectionFields: true,
          showPowerFields: true
        };
      }
    } catch (e) {
      console.error('获取表单配置失败:', e);
      // 默认表单配置
      return {
        showBasicFields: true,
        showControlFields: true,
        showProtectionFields: true,
        showPowerFields: true
      };
    }
  }
}

module.exports = ProjectDataBiz; 